package com.czm.art_light.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czm.art_light.annotation.DistributedLock;
import com.czm.art_light.constant.ArtErrorCodeEnum;
import com.czm.art_light.constant.CommonConsts;
import com.czm.art_light.context.UserActionHandlerChainContext;
import com.czm.art_light.entity.ArtUserLikes;
import com.czm.art_light.entity.ArtWork;
import com.czm.art_light.exception.BusinessException;
import com.czm.art_light.manager.mq.producer.AmqpMsgProducer;
import com.czm.art_light.mapper.ArtArtistMapper;
import com.czm.art_light.mapper.ArtUserLikesMapper;
import com.czm.art_light.mapper.ArtWorkMapper;
import com.czm.art_light.param.request.ArtUserLikesReqDto;
import com.czm.art_light.param.request.ArtWorkESReqDto;
import com.czm.art_light.param.request.PageReqDto;
import com.czm.art_light.param.request.UserActionReqDto;
import com.czm.art_light.param.response.ArtWorkBasicInfoRespDto;
import com.czm.art_light.param.response.PageRespDto;
import com.czm.art_light.param.response.RestResp;
import com.czm.art_light.service.ArtStatisticsService;
import com.czm.art_light.service.ArtUserLikesService;
import com.czm.art_light.util.UserHolderUtility;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户爱好信息 服务类
 */
@Service
public class ArtUserLikesServiceImpl implements ArtUserLikesService {
    @Autowired
    private ArtUserLikesMapper artUserLikesMapper;

    @Autowired
    private ArtStatisticsService artStatisticsService;

    @Autowired
    private ArtWorkMapper artWorkMapper;

    @Autowired
    private ArtArtistMapper artArtistMapper;

    @Autowired
    private AmqpMsgProducer amqpMsgProducer;

    @Autowired
    private UserActionHandlerChainContext userActionHandlerChainContext;

    /**
     * 修改喜好的状态
     */
    @DistributedLock(
            prefix = "updateUserLikeStatus",
            lockKey = "#artUserLikesReqDto.artWorkId"
    )
    @Override
    @Transactional
    public RestResp<Void> updateUserLikeStatus(ArtUserLikesReqDto artUserLikesReqDto) {
        Integer userId = UserHolderUtility.getUserId();
        //根据用户ID与艺术画作品ID
        ArtUserLikes artUserLikes = artUserLikesMapper.getByUserIdAndWorkId(userId, artUserLikesReqDto.getArtWorkId());
        if (artUserLikesReqDto.getIsLiked()) {
            //不喜欢---------------->喜欢
            //第一次修改
            if (artUserLikes == null) {
                //插入数据
                artUserLikesMapper.insert(ArtUserLikes.builder()
                        //用户id
                        .userId(userId)
                        //艺术画作品id
                        .workId(artUserLikesReqDto.getArtWorkId())
                        //是否喜欢
                        .isLiked(artUserLikesReqDto.getIsLiked())
                        .build());
                //喜欢量+1
//                artStatisticsService.incrementLikeCount(artUserLikesReqDto.getArtWorkId());
                //采用责任链嵌套策略设计模式，根据不同行为灵活执行相应业务逻辑。
                userActionHandlerChainContext.execute(new UserActionReqDto(userId, CommonConsts.ActionType.LIKE, artUserLikesReqDto.getArtWorkId()));
            } else {
                //和数据库的状态不一致才进行修改
                if (!artUserLikes.getIsLiked()) {
                    artUserLikesMapper.updateLikesByUserIdAndWorkId(userId, artUserLikesReqDto.getArtWorkId(), CommonConsts.LikeStatus.LIKE.getValue(), false);
                    //喜欢量+1
//                    artStatisticsService.incrementLikeCount(artUserLikesReqDto.getArtWorkId());
                    //采用责任链嵌套策略设计模式，根据不同行为灵活执行相应业务逻辑。
                    userActionHandlerChainContext.execute(new UserActionReqDto(userId, CommonConsts.ActionType.LIKE, artUserLikesReqDto.getArtWorkId()));
                }
            }
        } else {
            //喜欢---------------->不喜欢
            //该数据并没有在表中存在，则表示该请求是用户的恶意请求
            if (artUserLikes == null) {
                throw new BusinessException(ArtErrorCodeEnum.USER_MalicIOUS_BEHAVIOR);
            } else {
                //和数据库的状态不一致才进行修改
                if (artUserLikes.getIsLiked()) {
                    artUserLikesMapper.updateLikesByUserIdAndWorkId(userId, artUserLikesReqDto.getArtWorkId(), CommonConsts.LikeStatus.DISLIKE.getValue(), true);
                    //喜欢量-1
//                    artStatisticsService.decrementLikeCount(artUserLikesReqDto.getArtWorkId());
                    //采用责任链嵌套策略设计模式，根据不同行为灵活执行相应业务逻辑。
                    userActionHandlerChainContext.execute(new UserActionReqDto(userId, CommonConsts.ActionType.DISLIKE, artUserLikesReqDto.getArtWorkId()));

                }
            }
        }

        return RestResp.ok();
    }

    /**
     * 查询用户喜爱的所有艺术画作品
     */
    @Override
    public PageRespDto<ArtWorkBasicInfoRespDto> getUserLinksArtWork(PageReqDto pageReqDto) {
        //获取当前的用户id
        Integer userId = UserHolderUtility.getUserId();

        //构建分页对象
        Page<ArtUserLikes> page = new Page<>(pageReqDto.getPageNum(), pageReqDto.getPageSize());
        //根据userId以及分页信息查询喜欢的艺术作品的Id
        List<Integer> artWorkIdList = artUserLikesMapper.listArtWorkIdByUserId(page, userId);

        //再根据获取到的艺术作品id获取相关数据
        List<ArtWork> artWorks = new ArrayList<>();
        for (Integer id : artWorkIdList) {
            artWorks.add(artWorkMapper.getById(id));
        }

        //返回的对象
        List<ArtWorkBasicInfoRespDto> ArtWorkBasicList = new ArrayList<>();
        for (ArtWork artWork : artWorks) {
            //转换为基础信息返回DTO并添加到返回列表中
//            ArtWorkBasicList.add(new ArtWorkBasicInfoRespDto(artWork.getId(), artWork.getTitle(), artWork.getPrimaryImageSmallUrl()));
            ArtWorkBasicList.add(
                    ArtWorkBasicInfoRespDto.builder()
                            //作品的唯一标识ID
                            .id(artWork.getId())
                            //作品的名称
                            .title(artWork.getTitle())
                            //作品 艺术家名字
                            .artistName(artArtistMapper.getById(artWork.getArtistId()).getArtistName())
                            //作品的主图小图的URL
                            .primaryImageSmallUrl(artWork.getPrimaryImageSmallUrl())
                            .build());
        }
        return new PageRespDto<>(page.getPages(), page.getSize(), page.getTotal(), ArtWorkBasicList);
    }
}
